package cn.wolfcode.p2p.business.service.impl;
import cn.wolfcode.p2p.business.domain.PaymentScheduleDetail;
import java.util.Date;
import java.util.ArrayList;
import cn.wolfcode.p2p.base.domain.LoginInfo;

import java.math.RoundingMode;
import java.util.*;
import java.math.BigDecimal;
import java.util.concurrent.ConcurrentLinkedQueue;

import cn.wolfcode.p2p.base.domain.*;

import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.query.BidRequestQuery;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.business.domain.*;
import cn.wolfcode.p2p.business.mapper.BidMapper;
import cn.wolfcode.p2p.business.mapper.BidRequestMapper;
import cn.wolfcode.p2p.business.service.*;
import cn.wolfcode.p2p.util.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BidRequestServiceImpl implements IBidRequestService,ApplicationListener<ContextRefreshedEvent> {
        @Autowired
        private BidRequestMapper bidRequestMapper;
        @Autowired
        private IAccountService accountService;
        @Autowired
        private IUserInfoService userInfoService;
        @Autowired
        private IBidRequestAuditHistoryService bidRequestAuditHistoryService;
        @Autowired
        private IBidService bidService;
        @Autowired
        private IAccountFlowService accountFlowService;
        private  static final ConcurrentLinkedQueue<BidRequest> queue = new ConcurrentLinkedQueue<>();//安全的数组,避免高并发操作引发的问题
        @Autowired
        private ISystemAccountFlowService systemAccountFlowService;
        @Autowired
        private ISystemAccountService systemAccountService;
        @Autowired
        private IPaymentScheduleService paymentScheduleService;
        @Autowired
        private IpaymentScheduleDetailService paymentScheduleDetailService;
        @Autowired
        private ICreditTransferService creditTransferService;

        @Override
        public void borrowApply(BidRequest bidRequest) {
                //保存请求的方法
                LoginInfo loginInfo = UserContext.getLoginInfo();
                Long id = loginInfo.getId();
                Account account = accountService.getByid(id);
                UserInfo userinfo = userInfoService.getById(id);
                //判断最小金额,最大金额,最小利息,最大利息,最小投标金额,标题和内容不能为空
                AssertUtil.instance().isFalse(bidRequest.getBidRequestAmount().compareTo(Constants.BORROW_MIN_AMOUNT)<0,"最小借款数:"
                +Constants.BORROW_MIN_AMOUNT)
                        .isFalse(bidRequest.getCurrentRate().compareTo(Constants.BORROW_MIN_RATE)<0,"最小利率:"
                        +Constants.BORROW_MIN_RATE)
                        .isFalse(bidRequest.getCurrentRate().compareTo(Constants.BORROW_MAX_RATE)>0,"最大利率:"
                        +Constants.BORROW_MAX_RATE)
                        .isFalse(bidRequest.getMinBidAmount().compareTo(Constants.BID_MIN_AMOUNT)<0,"最小投标金额:"
                        +Constants.BID_MIN_AMOUNT)
                        .isNotNull(bidRequest.getTitle(),"借款标题必填")
                        .isNotNull(bidRequest.getDescription(),"借款内容必填")
                        .isFalse(bidRequest.getBidRequestAmount().compareTo(account.getBorrowLimitAmount())>0,"最大借款金额:"
                        +account.getBorrowLimitAmount())
                        .isFalse(userinfo.hasBorrow(),"您当前已经有借款申请!请联系客服!")
                        .isFalse(!userinfo.canBorrow(),"您还没有完成所有认证");
                //判断对象是否已经存在借款请求

                //保存
                BidRequest br = new BidRequest();
                br.setBidRequestType(bidRequest.getBidRequestType());
                br.setBidRequestAmount(bidRequest.getBidRequestAmount());
                br.setCurrentRate(bidRequest.getCurrentRate());
                br.setMonthes2Return(bidRequest.getMonthes2Return());
                br.setTitle(bidRequest.getTitle());
                br.setDescription(bidRequest.getDescription());
                br.setCreateUser(loginInfo);
                br.setDisableDays(bidRequest.getDisableDays());
                br.setMinBidAmount(bidRequest.getMinBidAmount());
                br.setApplyTime(new Date());
                BigDecimal total = CalculatetUtil.calTotalInterest(bidRequest.getReturnType(), bidRequest.getBidRequestAmount()
                        , bidRequest.getCurrentRate(), bidRequest.getMonthes2Return());
                br.setTotalRewardAmount(total);
                bidRequestMapper.insert(br);//新增
                //更改USERINFO
                userinfo.addBitState(BitStatesUtils.HAS_BIDREQUEST_IN_PROCESS);
                userInfoService.update(userinfo);
        }

        @Override
        public PageResult selectForList(BidRequestQuery qo) {
                 //先查出COunt,如果COUNT为0,返回空集合
                if(qo.getState()==-1){
                        qo.setBidRequestStates(new Integer[]{Constants.BIDREQUEST_STATE_BIDDING,Constants.BIDREQUEST_STATE_COMPLETE_PAY_BACK});
                }
                 int row = bidRequestMapper.selectCount(qo);
                 if(row==0){
                     return new PageResult(Collections.EMPTY_LIST,0,1,qo.getPageSize());
                 }
                 List<BidRequest> list =bidRequestMapper.query(qo);
                 return new PageResult(list,row,qo.getCurrentPage(),qo.getPageSize());
        }

        @Override
        public BidRequest getById(Long id) {
                return bidRequestMapper.selectByPrimaryKey(id);
        }

        @Override
        public void publishAudit(Long id, String remark, Integer state, Date publishTime) {
                //判断基本参数
                //判断是否存于待审核
                BidRequest bidRequest = bidRequestMapper.selectByPrimaryKey(id);


                AssertUtil.instance().isFalse(bidRequest.getBidRequestState()!=Constants.BIDREQUEST_STATE_APPLY,
                        "借款不存于待审核!请联系客服!");
                //设置公共参数
                //保存审核历史记录对象,不管成功还是失败都要保存的
                bidRequestAuditHistoryService.save(bidRequest,remark,state, BidRequestAuditHistory.AUDITTYPE_PUBLISH);
                bidRequest.setNote(remark);
                //如果审核通过的操作
                if(state== BaseAudit.STATE_SUCCESS){
                        //指定发标时间
                        if(publishTime!=null){
                                bidRequest.setBidRequestState(Constants.BIDREQUEST_STATE_PUBLISH_PENDING);
                                bidRequest.setPublishTime(publishTime);
                        }else{   //立刻发标
                                bidRequest.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                                bidRequest.setPublishTime(new Date());
                        }
                        bidRequest.setDisableDate(DateUtils.addDays(bidRequest.getPublishTime(),bidRequest.getDisableDays()));
                }else{   //审核失败的操作
                        //删除用户的位状态\
                        UserInfo userInfo = userInfoService.getById(bidRequest.getCreateUser().getId());
                        userInfo.removeBitState(BitStatesUtils.HAS_BIDREQUEST_IN_PROCESS);
                        userInfoService.update(userInfo);
                        //修改借款状态为失败
                        bidRequest.setBidRequestState(Constants.BIDREQUEST_STATE_PUBLISH_REFUSE);
                }


                update(bidRequest);
                //把审核成功且等待发标状态的对象装到队列,要预防乐观锁报错
                if(publishTime!=null && state==BaseAudit.STATE_SUCCESS){
                        bidRequest.setVersion(bidRequest.getVersion()+1);
                        queue.offer(bidRequest);
                }
        }

        private void update(BidRequest bidRequest) {
                AssertUtil.instance().isFalse(bidRequestMapper.updateByPrimaryKey(bidRequest)==0,"修改借款信息异常!请联系客服!");
        }

        @Override
        public List<BidRequest> queryPublishPendng() {
                BidRequestQuery qo = new BidRequestQuery();
                qo.setState(Constants.BIDREQUEST_STATE_PUBLISH_PENDING);
                qo.setOrderBy("br.publish_time ASC");
                qo.setPageSize(5);
                List<BidRequest> list = bidRequestMapper.query(qo);
                return list;
        }

        @Override
        public List<BidRequest> listBidRequestBiding() {
                BidRequestQuery qo = new BidRequestQuery();
                qo.setBidRequestStates(new Integer[]{Constants.BIDREQUEST_STATE_BIDDING,Constants.BIDREQUEST_STATE_PAYING_BACK,
                        Constants.BIDREQUEST_STATE_COMPLETE_PAY_BACK});
                qo.setOrderBy("br.bid_request_state ASC");
                qo.setPageSize(5);
                List<BidRequest> list = bidRequestMapper.query(qo);
                return list;
        }

        public void selectPublishBidRequestToQueue(){
                List<BidRequest> list = bidRequestMapper.selectPublishBidRequests(Constants.BIDREQUEST_STATE_PUBLISH_PENDING);
                for (BidRequest br : list) {
                        if(!queue.contains(br)){
                                queue.offer(br);//如果没有重叠,就加入队列
                        }
                }
        }
        /**
         * 系统启动的时候查询数据库,把所有待发标的查出来加进队列
         * @param event
         */
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
                System.out.println("系统启动,查待发标");
                selectPublishBidRequestToQueue();
        }

        /**
         * 遍历队列,拿出到发标时间的对象,改状态
         */
        public void checkPublishBidRequestForQueue(){

                Iterator<BidRequest> it = queue.iterator();
                Date now = new Date();
                while (it.hasNext()){
                        BidRequest br = it.next();
                        if(br.getPublishTime().before(now)){
                                br.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                                update(br);
                                it.remove();
                        }
                }
        }


        @Override
        public void bid(Long bidRequestId, BigDecimal amount) {
                //判断是不是处于招标中,判断金额
                AssertUtil.instance().isNotNull(amount,"参数异常!请联系客服!");
                //投标金额要小于等用户用户的可用余额
                LoginInfo bider = UserContext.getLoginInfo();//投标人
                Account account = accountService.getByid(bider.getId());
                AssertUtil.instance().isFalse(account.getUsableAmount().compareTo(amount)<0,"投标金额超过可用余额!");
                //投标金额必须小于剩余投标金额
                BidRequest br = bidRequestMapper.selectByPrimaryKey(bidRequestId);
                AssertUtil.instance().isFalse(br.getRemainAmount().compareTo(amount)<0,"剩余投标金额:"+br.getRemainAmount());
                //当前用户对该标总投资不能超过借款总金额的百分之50，
                //通过用户ID和借款ID获取用户对这个借款的总投资
                BigDecimal sum = bidService.getUserBidSumByBidRequestId(bider.getId(),bidRequestId);
                BigDecimal bidToTalAmount = sum.add(amount);
                BigDecimal tempAmount = br.getBidRequestAmount().multiply(new BigDecimal("0.5"));//借款总额的百分之50
                AssertUtil.instance().isFalse(bidToTalAmount.compareTo(tempAmount)>0,"个人对这个借款的最大投资金额为:"+tempAmount+",您当前还可以投资"+
                        tempAmount.subtract(sum)+"元");
                //如果剩余投标金额小于最小投标，只能一次性把剩余的投完
                if(br.getRemainAmount().compareTo(br.getMinBidAmount())<0){
                        AssertUtil.instance().isFalse(amount.compareTo(br.getRemainAmount())!=0,"当前只能投标金额:"+br.getRemainAmount());
                }else{
                //否则这次投标金额不能低于最小投标金额
                        AssertUtil.instance().isFalse(amount.compareTo(br.getMinBidAmount())<0,"投标金额不能低于最小投标金额");
                }
                //借款状态要处于招标中
                AssertUtil.instance().isFalse(br.getBidRequestState()!=Constants.BIDREQUEST_STATE_BIDDING,"借款状态不处于招标中!");
                //本人不能投标
                AssertUtil.instance().isFalse(bider.getId().longValue()==br.getCreateUser().getId().longValue(),"借款本人不能投标!");
                //创建一个投标记录，service
                bidService.createBid(br,amount,bider);
                //投资人
                //投资人账户可用余额较少,冻结金额增加
                account.subtractUsableAmount(amount);
                account.addFreezedAmount(amount);
                accountService.update(account);
                //创建投标流水,
                accountFlowService.createBidFreezedFlow(amount,account);

                //借款对象的投标次数增加
                br.setBidCount(br.getBidCount()+1);
                //投标总额增加
                br.setCurrentSum(br.getCurrentSum().add(amount));

                //如果已经满标
                if(br.getBidRequestAmount().compareTo(br.getCurrentSum())==0){
                        //借款对象状态修改为满标一审
                        br.setBidRequestState(Constants.BIDREQUEST_STATE_APPROVE_PENDING_1);
                        //这个借款下的投标记录的状态修改为满标一审,多个的对象修改
                        bidService.batchUpdateState(br.getId(),Constants.BIDREQUEST_STATE_APPROVE_PENDING_1);
                }
                //更新对象
                bidRequestMapper.updateByPrimaryKey(br);
        }

        @Override
        public void fullAudit1(Long id, String remark, Integer state) {
                //判断基本参数
                //是否处于一审状态
                BidRequest br = bidRequestMapper.selectByPrimaryKey(id);
                AssertUtil.instance().isFalse(br.getBidRequestState()!=Constants.BIDREQUEST_STATE_APPROVE_PENDING_1,"当前借款不处于满标一审");
                //设置相关审核信息,保存审核历史对象
                bidRequestAuditHistoryService.save(br,remark,state,BidRequestAuditHistory.AUDITTYPE_AUDIT1);
                //如果成功
                if(state==BaseAudit.STATE_SUCCESS){
                        //借款状态修改为二审
                        br.setBidRequestState(Constants.BIDREQUEST_STATE_APPROVE_PENDING_2);
                        //所有这个借款的投标状态改为二审
                        bidService.batchUpdateState(br.getId(),Constants.BIDREQUEST_STATE_APPROVE_PENDING_2);
                }else{
                        bidRequestReject(br);


                }
                bidRequestMapper.updateByPrimaryKey(br);
        }

        public void bidRequestReject(BidRequest br) {
                //如果失败
                //修改借款状态为二审失败
                br.setBidRequestState(Constants.BIDREQUEST_STATE_REJECTED);
                //修改投标状态为二审失败
                bidService.batchUpdateState(br.getId(),Constants.BIDREQUEST_STATE_REJECTED);
                //退钱
                //冻结资金减少,可用余额增加
                ///创建投标失败解冻流水
                //第一种方法
                        /*for (Bid bid : br.getBids()) {
                                Account account = accountService.getByid(bid.getBidUser().getId());
                                account.addUsableAmount(bid.getAvailableAmount());//加回投标的金额
                                account.subtractFreezedAmount(bid.getAvailableAmount());//;减少冻结
                                accountService.update(account);
                                accountFlowService.createBidFailureFlow(bid.getAvailableAmount(),account);
                        }*/
                Map<Long, Account> map = new HashMap<>();
                List<Bid> bids = br.getBids();
                for (Bid bid : bids) {
                        Long biderId = bid.getBidUser().getId();//投标者的Id
                        Account account = map.get(biderId);
                        if(account==null){ //如果从MAP里拿到的是null
                                account = accountService.getByid(biderId);
                                map.put(biderId,account);
                        }
                        account.addUsableAmount(bid.getAvailableAmount());//加回投标的金额
                        account.subtractFreezedAmount(bid.getAvailableAmount());//;减少冻结
                        accountFlowService.createBidFailureFlow(bid.getAvailableAmount(),account,br);
                }
                for (Account account : map.values()) {
                        accountService.update(account);
                }

                //移除用户的借款位状态
                UserInfo bidRequestCreater = userInfoService.getById(br.getCreateUser().getId());
                bidRequestCreater.removeBitState(BitStatesUtils.HAS_BIDREQUEST_IN_PROCESS);
                userInfoService.update(bidRequestCreater);
        }

        @Override
        public void fullAudit2(Long id, String remark, Integer state) {
                //判断借款对象处于二审
                BidRequest br = bidRequestMapper.selectByPrimaryKey(id);
                //设置审核相关信息,保存一个审核历史记录
                bidRequestAuditHistoryService.save(br,remark,state,BidRequestAuditHistory.AUDITTYPE_AUDIT2);


                if(state==BaseAudit.STATE_SUCCESS){
                        //如果成功
                        //1借款对象状态改为还款中
                        br.setBidRequestState(Constants.BIDREQUEST_STATE_PAYING_BACK);
                        //2投标对象全部改成还款中
                        bidService.batchUpdateState(br.getId(),Constants.BIDREQUEST_STATE_PAYING_BACK);

                        //3借款人
                        Long borrowerId = br.getCreateUser().getId();//借款人Id
                        Account borrowerAccount = accountService.getByid(borrowerId);
                        //1收到借款,可用余额增加
                        borrowerAccount.addUsableAmount(br.getBidRequestAmount());
                        //2,创建收到借款金额流水
                        accountFlowService.createBorrowSuccessFlow(br.getBidRequestAmount(),borrowerAccount,br);
                        //3移除借款人借款位状态
                        UserInfo userInfo = userInfoService.getById(borrowerId);
                        userInfo.removeBitState(BitStatesUtils.HAS_BIDREQUEST_IN_PROCESS);
                        userInfoService.update(userInfo);
                        //5减少借款人的剩余授信额度
                        borrowerAccount.setRemainBorrowLimit(borrowerAccount.getRemainBorrowLimit().subtract(br.getBidRequestAmount()));
                        //6,借款人的待还本息增加,借到的钱加总利息
                        borrowerAccount.setUnReturnAmount(borrowerAccount.getUnReturnAmount()
                        .add(br.getBidRequestAmount()).add(br.getTotalRewardAmount()));
                        //7借款人支付平台借款管理费,可用余额较少
                        BigDecimal borrowAccountManagementCharge = CalculatetUtil.calAccountManagementCharge(br.getBidRequestAmount());
                        borrowerAccount.subtractUsableAmount(borrowAccountManagementCharge);
                        ///8创建支付管理费流水
                        accountFlowService.createBorrowAccountManagementChargeFlow(borrowAccountManagementCharge,borrowerAccount,br);
                        //更新借款人账户
                        accountService.update(borrowerAccount);//更新借款人账户
                        //4,投资人
                        Map<Long,Account> accounts = new HashMap<>();
                        List<Bid> bids = br.getBids();//借款里的投资人
                        for (Bid bid : bids) {
                                Long bidId = bid.getBidUser().getId();
                                Account biderAccount = accounts.get(bidId);
                                if(biderAccount==null){
                                        biderAccount = accountService.getByid(bidId);
                                        accounts.put(bidId,biderAccount);
                                }
                                //1冻结金额较少
                                biderAccount.subtractFreezedAmount(bid.getAvailableAmount());
                                //2创建投标成功,解冻流水
                                accountFlowService.createBidSuccessFlow(biderAccount,bid.getAvailableAmount(),br);
                                //3代收本金增加
                                biderAccount.setUnReceivePrincipal(biderAccount.getUnReceivePrincipal().add(bid.getAvailableAmount()));
                                //4待收利息增加 投标金额/借款总额*总利息
                                BigDecimal unReceiveInterest = bid.getAvailableAmount().divide(br.getBidRequestAmount(),Constants.SCALE_CAL, RoundingMode.HALF_UP).multiply(br.getTotalRewardAmount());

                                biderAccount.setUnReceiveInterest(biderAccount.getUnReceiveInterest()
                                        .add(unReceiveInterest.setScale(Constants.SCALE_CAL, RoundingMode.HALF_UP)));
                        }
                        //修改投资人账户
                        for (Account account : accounts.values()) {
                                accountService.update(account);
                        }


                        //4位借款人创建还款计划
                        //拿到期数
                        paymentScheduleService.createPaymentSchedule(br);

                        //5位投资人创建收款计划

                        //平台
                        SystemAccount systemAccount = systemAccountService.getSystemAccount();
                        systemAccount.setUsableAmount(systemAccount.getUsableAmount().add(borrowAccountManagementCharge));
                        //平台收到借款人的接口管理费,可用余额增加
                        systemAccountService.update(systemAccount);
                        //创建平台收取管理费流水
                        systemAccountFlowService.createBidRequestManagementCharge(systemAccount,borrowAccountManagementCharge,br);

                }else{
                        bidRequestReject(br);


                }
                bidRequestMapper.updateByPrimaryKey(br);//更新借款对象信息
        }

        @Override
        public void returnMoner(Long id) {
                //判断参数
                AssertUtil.instance().isNotNull(id,"参数异常");
                //判断当前还款状态处于待还或者逾期
                PaymentSchedule ps = paymentScheduleService.getById(id);
                AssertUtil.instance().isFalse(ps.getState()==Constants.PAYMENT_STATE_DONE,"当前期已还");
                //判断还款人的可用余额
                LoginInfo borrower = UserContext.getLoginInfo();
                Account borrowerAccount = accountService.getByid(borrower.getId());
                AssertUtil.instance().isFalse(borrowerAccount.getUsableAmount().compareTo(ps.getTotalAmount())<0,
                        "账户可用余额不足还款").isFalse(borrower.getId().longValue()!=ps.getBorrowUser().getId().longValue(),
                        "还款要自己来!");
                //只能借款人自己能还款

                //执行还款
                //借款人
                //可用余额减少
                borrowerAccount.subtractUsableAmount(ps.getTotalAmount());
                //还款流水
                accountFlowService.createReturnMoneyFlow(borrowerAccount,ps);
                //修改当前还款计划状态为已还
                ps.setState(Constants.PAYMENT_STATE_DONE);
                //修改还款时间
                ps.setPayDate(new Date());
                //借款人剩余授信额度增加,还多少,加多少
                paymentScheduleService.update(ps);//更新还款计划对象
                borrowerAccount.setRemainBorrowLimit(borrowerAccount.getRemainBorrowLimit().add(ps.getTotalAmount()));
                //借款人待还本息减少
                borrowerAccount.setUnReturnAmount(borrowerAccount.getUnReturnAmount().subtract(ps.getTotalAmount()));
                accountService.update(borrowerAccount);//更新借款人账户信息
                //投资人
                SystemAccount systemAccount = systemAccountService.getSystemAccount();
                Map<Long,Account> accounts = new HashMap<>();
                List<PaymentScheduleDetail> psds = ps.getPaymentScheduleDetails();
                for (PaymentScheduleDetail psd : psds) {
                        Long biderId = psd.getToLoginInfoId();
                        Account account = accounts.get(biderId);
                        if(account==null){
                                account = accountService.getByid(biderId);
                                accounts.put(biderId,account);
                        }
                        //收钱,可用余额增加,.list ,多个bid
                        account.addUsableAmount(psd.getTotalAmount());
                        // 创建收款流水
                        accountFlowService.createCollectionFlow(account,ps.getTotalAmount(),ps);
                        //待收本金减少
                        account.setUnReceivePrincipal(account.getUnReceivePrincipal().subtract(psd.getPrincipal()));
                        //待收利息减少
                        account.setUnReceiveInterest(account.getUnReceiveInterest().subtract(psd.getInterest()));
                        //收款计划修改收款时间
                        psd.setPayDate(new Date());
                        paymentScheduleDetailService.update(psd);//更新还款计划对象
                        //支付平台管理费
                        BigDecimal interestManagerCharge = CalculatetUtil.calInterestManagerCharge(psd.getInterest());
                        account.subtractUsableAmount(interestManagerCharge);
                        //创建流水
                        accountFlowService.createInterestManagerChargeFlow(account,interestManagerCharge);
                        //平台,收取管理费
                        systemAccount.setUsableAmount(systemAccount.getUsableAmount().add(interestManagerCharge));
                        //创建流水
                        systemAccountFlowService.createInterestManagerChargeFlow(systemAccount,interestManagerCharge);
                        if(psd.getTransferState()==PaymentScheduleDetail.TANSFER_STATE_TRANSFERING){
                                CreditTransfer creditTransfer = creditTransferService.getByBidIdAndFromLoginInfoIdAndState(psd.getBidId(),psd.getToLoginInfoId()
                                        ,Constants.BIDREQUEST_STATE_BIDDING);
                                creditTransfer.setBidRequestState(Constants.BIDREQUEST_STATE_UNDO);
                                creditTransferService.update(creditTransfer);
                                paymentScheduleDetailService.batchUpdateTransferState(new Long[]{psd.getBidId()},PaymentScheduleDetail.TANSFER_STATE_NORMAL);
                        }

                }
                systemAccountService.update(systemAccount);//更新系统账户
                //更新投资人账户
                for (Account account : accounts.values()) {
                        accountService.update(account);
                }

                int count = paymentScheduleService.getReturnSuccessMonthIndexNumber(ps.getBidRequestId(),Constants.PAYMENT_STATE_DONE);
                //如果已经还清,查询当前借款里的所有还款计划是已还清的数量等于分期数量
                BidRequest bidRequest = getById(ps.getBidRequestId());
                if(count==bidRequest.getMonthes2Return()){
                        bidRequest.setBidRequestState(Constants.BIDREQUEST_STATE_COMPLETE_PAY_BACK);
                        bidService.batchUpdateState(bidRequest.getId(),Constants.BIDREQUEST_STATE_COMPLETE_PAY_BACK);
                        update(bidRequest);

                }
                //修改借款对象状态为已还清
                //批量修改投标对象的状态为已还清




        }


}
